package cn.supermarket.service.impl;

import cn.supermarket.ex.ServiceException;
import cn.supermarket.mapper.RetailMapper;
import cn.supermarket.mapper.RetailOrMapper;
import cn.supermarket.pojo.dto.PaymentAddNewDTO;
import cn.supermarket.pojo.dto.RetailDetailsDTO;
import cn.supermarket.pojo.entity.Retail;
import cn.supermarket.pojo.entity.RetailOr;
import cn.supermarket.pojo.vo.RetailDetailVO;
import cn.supermarket.pojo.vo.RetailPlainVO;
import cn.supermarket.pojo.vo.StockDetailedVO;
import cn.supermarket.service.iservice.IPaymentService;
import cn.supermarket.service.iservice.IRetailService;
import cn.supermarket.service.iservice.IStockService;
import cn.supermarket.utils.GetDateTime;
import cn.supermarket.utils.GetInfoUtils;
import cn.supermarket.utils.SnowFlakeGenerateIdWorker;
import cn.supermarket.web.State;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RetailServiceImpl implements IRetailService {

    @Autowired
    private RetailMapper retailMapper;

    @Autowired
    private RetailOrMapper retailOrMapper;

    @Autowired
    private IStockService stockService;

    @Autowired
    GetDateTime getDateTime;

    @Autowired
    private IPaymentService paymentService;

    //添加零售
    @Transactional
    @Override
    public void addNew( RetailDetailsDTO retailDetailsDTO) {
        Retail retail = new Retail();
        SnowFlakeGenerateIdWorker s = new SnowFlakeGenerateIdWorker(7, 2);
        SnowFlakeGenerateIdWorker x = new SnowFlakeGenerateIdWorker(2, 1);
        Long id = s.nextId();
        String or = x.generateNextId();
        BeanUtils.copyProperties(retailDetailsDTO, retail);
        retail.setId(id);
        LocalDateTime now = LocalDateTime.now();
        retail.setOrderNumber(or);
        retail.setData(now);
        retail.setCreateDate(now);
        retail.setLastUpdateTime(now);
        retail.setIsEnable(0);
        retail.setIsDisplay(1);
        retail.setIsCancel(0);
      /*  List<RetailOr> retails = retailDetailsDTO.getRetails();
        if (retails==null||retails.isEmpty()){
            throw new ServiceException(State.ERR_NOT_FOUND, "未收到");
        }*/
        List<RetailOr> st = new ArrayList<>();
        BigDecimal PaymentAmount = new BigDecimal(0);

            RetailOr retailOr1 = new RetailOr();
            BeanUtils.copyProperties(retailDetailsDTO, retailOr1);

            StockDetailedVO stockDetailedVO = stockService.selectStockDetailedVOByProductId(retailOr1.getProductId());
            retailOr1.setPrice(stockDetailedVO.getSellingPrice());
            retailOr1.setTitle(stockDetailedVO.getProductName());
            retailOr1.setUnit(stockDetailedVO.getUnit());
            retailOr1.setRetailId(id);
            retailOr1.setId(s.nextId());
            PaymentAmount = PaymentAmount.add(retailOr1.getPrice().multiply(retailOr1.getQuantity()))
                    .multiply(stockDetailedVO.getDiscountPrice()).subtract(stockDetailedVO.getDiscountPrice());
            stockService.reduceProductCount(retailOr1.getProductId(), retailOr1.getQuantity());
            st.add(retailOr1);

        GetInfoUtils getInfoUtils = new GetInfoUtils();
        GetInfoUtils userInfo = getInfoUtils.getUserInfo();
        retail.setHandler(userInfo.getUsername());
        retail.setPaymentAmount(PaymentAmount);
        retail.setAmountPayable(PaymentAmount);

        retailOrMapper.insertRetail(st);
        int rows = retailMapper.addNewRetail(retail);
        if (rows != 1) {
            throw new ServiceException(State.ERR_UNKNOWN_ERROR, "未知错误导致修改失败，请稍后再试");
        }
        PaymentAddNewDTO paymentAddNewDTO = new PaymentAddNewDTO();
        BeanUtils.copyProperties(retailDetailsDTO, paymentAddNewDTO);
        paymentAddNewDTO.setOrderNumber(or);
        paymentAddNewDTO.setDate(now);
        paymentAddNewDTO.setPayee("贼挣钱超市");
        paymentAddNewDTO.setPayer("散客");
        paymentAddNewDTO.setPaymentAmount(PaymentAmount);
        paymentService.addNewPayment(paymentAddNewDTO);

    }

    //修改备注
    @Override
    public void updateByOther(Long id, String other) {
        RetailPlainVO byId = retailMapper.getById(id);
        if (byId == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "所查类别不存在");
        }
        int rows = retailMapper.updateByOther(id, other);
        GetInfoUtils getInfoUtils = new GetInfoUtils();
        GetInfoUtils userInfo = getInfoUtils.getUserInfo();
        retailMapper.updateByHandler(userInfo.getUsername(), id);
        if (rows != 1) {
            throw new ServiceException(State.ERR_UNKNOWN_ERROR, "未知错误导致修改失败，请稍后再试");
        }
        retailMapper.updateByLastUpdateTime(id, LocalDateTime.now());
    }

    //修改是否可见
    @Override
    public void updateByIsDisplay(Long id, Integer isDisplay) {
        RetailPlainVO byId = retailMapper.getById(id);
        if (byId == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "所查类别不存在");
        }
        if (byId.getIsDisplay().equals(isDisplay)) {
            throw new ServiceException(State.ERR_REPEAT_UPDATE, "该操作为无效的重复操作");
        }
        if (isDisplay == 1 || isDisplay == 0) {
            retailMapper.updateByIsDisplay(id, isDisplay);
            retailMapper.updateByLastUpdateTime(id, LocalDateTime.now());
            GetInfoUtils getInfoUtils = new GetInfoUtils();
            GetInfoUtils userInfo = getInfoUtils.getUserInfo();
            retailMapper.updateByHandler(userInfo.getUsername(), id);
        } else {
            throw new ServiceException(State.ERR_BAD_REQUEST, "参数错误");
        }
    }

    //作废
    @Override
    public void updateByIsCancel(Long id) {
        RetailPlainVO byId = retailMapper.getById(id);
        if (byId == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "所查类别不存在");
        }
        retailMapper.updateByIsCancel(id);
        retailMapper.updateByLastUpdateTime(id, LocalDateTime.now());
        GetInfoUtils getInfoUtils = new GetInfoUtils();
        GetInfoUtils userInfo = getInfoUtils.getUserInfo();
        retailMapper.updateByHandler(userInfo.getUsername(), id);

    }

    //是否启用
    @Override
    public void updateByIsEnable(Long id, Integer isEnable) {
        RetailPlainVO byId = retailMapper.getById(id);
        if (byId == null) {
            throw new ServiceException(State.ERR_NOT_FOUND, "所查类别不存在");
        }
        if (byId.getIsEnable().equals(isEnable)) {
            throw new ServiceException(State.ERR_REPEAT_UPDATE, "该操作为无效的重复操作");
        }
        if (isEnable == 1 || isEnable == 0) {
            retailMapper.updateByIsEnable(id, isEnable);
            retailMapper.updateByLastUpdateTime(id, LocalDateTime.now());
            GetInfoUtils getInfoUtils = new GetInfoUtils();
            GetInfoUtils userInfo = getInfoUtils.getUserInfo();
            retailMapper.updateByHandler(userInfo.getUsername(), id);
        } else {
            throw new ServiceException(State.ERR_BAD_REQUEST, "参数错误");
        }
    }

    //订单号查询
    @Override
    public List<RetailDetailVO> getByOrderNumber(String orderNumber) {
        List<RetailDetailVO> byOrderNumber = retailMapper.getByOrderNumber(orderNumber);
        if (byOrderNumber==null){
            throw new ServiceException(State.ERR_NOT_FOUND, "该零售单不存在");
        }

        return byOrderNumber;
    }

    //日期查询
    @Override
    public List<RetailDetailVO> getByData(Date dateStart, Date dateEnd) {
        List<RetailDetailVO> byData = retailMapper.getByData(getDateTime.getDateStart(dateStart), getDateTime.getDateEnd(dateEnd));
        if (byData==null){
            throw new ServiceException(State.ERR_NOT_FOUND, "该时间段没有零售记录");
        }
        return byData;
    }

    //金额范围查询
    @Override
    public List<RetailDetailVO> getByPaymentAmount(BigDecimal initialAmount, BigDecimal finish) {
        List<RetailDetailVO> byPaymentAmount = retailMapper.getByPaymentAmount(initialAmount, finish);
        if (byPaymentAmount==null){
            throw new ServiceException(State.ERR_NOT_FOUND, "该金额段没有零售记录");
        }
        return byPaymentAmount;
    }




}
